<template>
  <div class="fulltable">
    <div class="full">
      <div class="add" v-if="isSuperman">  
        <button class="button" @click="dialogVisible = true">➕新增</button>  
      </div>  
<div class="search-box">  
  <el-input v-model="searchQuery" placeholder="搜索职位名称" style="width:200px;margin-right: 10px;"  @keyup.enter="search" clearable></el-input>  
</div>
    <el-table
    :data="filteredData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
    :height="tableHeight"
    border
    style="width: 100%">
    <el-table-column
      prop="position"
      label="职称"
      width="180"
      >
    </el-table-column>
    <el-table-column
      prop="level"
      label="职级"
      width="180">
    </el-table-column>
     <el-table-column
      prop="desc"
      label="描述"
      width="180">
    </el-table-column>
        <el-table-column
      prop="salary"
      label="工资"
      :width="isSuperman ? '180' : ''"
      >
    </el-table-column>
        <el-table-column label="操作" v-if="isSuperman">  
          <template slot-scope="scope">  
            <el-button type="primary" size="small" @click="editItem(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteItem(scope.row)">删除</el-button>  
          </template>  
        </el-table-column>  
  </el-table>
      <div class="paging">
      <el-pagination  
        @size-change="handleSizeChange"  
        @current-change="handleCurrentChange"  
        :current-page="currentPage"  
        :page-sizes="[5,10, 20, 40, 60]"  
        :page-size="pageSize"  
        :pager-count="4"  
        layout="total, sizes, prev, pager, next, jumper"  
        :total="filteredData.length">  <!-- 使用 filteredData.length -->  
      </el-pagination>  
      </div>
  </div>

<el-dialog title="新增选项" :visible.sync="dialogVisible" width="30%">  
  <el-form :model="newOption" :rules="rules" ref="newDeptForm" label-width="80px">  
    <el-form-item label="职称" prop="position">  
      <el-input v-model="newOption.position"></el-input>  
    </el-form-item>  
    <el-form-item label="职级"  prop="level" >  
      <el-input v-model="newOption.level" placeholder="必须为数字,数字越小职级越高"></el-input>  
    </el-form-item>  
    <el-form-item label="描述" prop="desc">  
      <el-input v-model="newOption.desc"></el-input>  
    </el-form-item>  
    <el-form-item label="工资" prop="salary">  
      <el-input v-model="newOption.salary"></el-input>  
    </el-form-item>  
  </el-form>  
  <div slot="footer" class="dialog-footer">  
    <el-button @click="dialogVisible = false">取 消</el-button>  
    <el-button type="primary" @click="saveNewOption">确 定</el-button>  
  </div>  
</el-dialog>

<el-dialog title="编辑职位" :visible.sync="editDialogVisible" width="30%">  
  <el-form :model="editOption"  ref="editForm" label-width="80px">  
    <el-form-item label="职称" prop="position">  
      <el-input v-model="editOption.position"></el-input>  
    </el-form-item>  
    <el-form-item label="职级" prop="level">  
      <el-input v-model="editOption.level" placeholder="必须为数字,数字越小职级越高"></el-input>  
    </el-form-item>  
    <el-form-item label="描述" prop="desc">  
      <el-input v-model="editOption.desc"></el-input>  
    </el-form-item>  
    <el-form-item label="工资" prop="salary">  
      <el-input v-model="editOption.salary"></el-input>  
    </el-form-item>  
  </el-form>  
  <div slot="footer" class="dialog-footer">  
    <el-button @click="editDialogVisible = false">取 消</el-button>  
    <el-button type="primary" @click="saveEditOption">确 定</el-button>  
  </div>  
</el-dialog>
  </div>
</template>

<script>
import {getOptionList,addOption,deleteOptionById, updateOption} from '@/api/option';
import {getDeptList} from '@/api/dept';
import { jwtDecode } from 'jwt-decode'; 
import {addLog} from '@/api/log';
export default {
  data(){
    return {
        optionData:[],
        currentPage: 1,  
        pageSize: 5  ,
        tableHeight: 300,  
        maxTableHeight: 700, // 最大高度 600px  
        minTableHeight: 300,
        dialogVisible: false, // 新增的属性
        isSuperman: this.checkUserRole(), // 检查用户角色并设置 
        searchQuery: '',  // 用于存储搜索输入  
        newOption: { // 新增的属性,用于存储新建的选项信息  
          position: '',  
          level: '',  
          desc: '',  
          salary: '',
          dept:null
        },
        logItem:{
              mn:'',
              opn:'',
              res:''
      },
        rules: {  
          position: [  
            { required: true, message: '请输入职称', trigger: 'blur' }  
          ],  
          level: [  
            { required: true, message: '请输入等级', trigger: 'blur' },  
                { validator: (rule, value, callback) => {  
                if (isNaN(value)) {  
                  callback(new Error('等级必须为数字'));  
                } else {  
                  callback();  
                }  
              }, trigger: 'blur' }  
          ],  
          desc: [  
            { required: true, message: '请输入描述', trigger: 'blur' }  
          ],  
          salary: [  
            { required: true, message: '请输入工资', trigger: 'blur' },  
            { validator: (rule, value, callback) => {  
              if (isNaN(value)) {  
                callback(new Error('工资必须为数字'));  
              } else {  
                callback();  
              }  
            }, trigger: 'blur' }  
          ]
        },
        editDialogVisible: false,
        editOption: {
          id: '',
          position: '',
          level: '',
          desc: '',
          salary: '',
        },
    }
  },
  created(){
    getOptionList().then(response=>{
      this.optionData = response.data
      this.calculateTableHeight() 
      console.log(response.data)
    }).catch(error =>{
      console.log(error)
      this.tableHeight = this.minTableHeight 
    })
  },
  watch:{
  currentPage() {  
    this.calculateTableHeight();  
  },  
  pageSize() {  
    this.calculateTableHeight();  
  },  
  searchQuery() {  // 监听 searchQuery 的变化  
    this.currentPage = 1;  // 重置当前页为 1  
    this.calculateTableHeight();  // 重新计算表格高度  
  }  
  },
  computed: {  
  filteredData() {  
    if (!this.searchQuery) {  
      return this.optionData;  // 如果没有搜索关键词，返回全部数据  
    }  
    return this.optionData.filter(item =>  
      item.position.toLowerCase().includes(this.searchQuery.toLowerCase())  
    );  
  }  
},
  methods:{
    handleSizeChange(val) {  
      this.pageSize = val;  
      this.currentPage = 1;  
      this.logItem.mn = "handleSizeChange";
      this.logItem.opn = "改变每页显示的职位数量";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
    handleCurrentChange(val) {  
      this.currentPage = val;
      this.logItem.mn = "handleCurrentChange";
      this.logItem.opn = "改变页码-职位管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
calculateTableHeight() {  
  // 获取当前页展示的过滤后数据量  
  const currentPageData = this.filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);  
  
  // 每行高度为 60px，再加上表头高度 50px，得到总高度  
  let height = (currentPageData.length + 1) * 60;  
  // 限制高度在 minTableHeight 和 maxTableHeight 之间  
  this.tableHeight = Math.max(this.minTableHeight, Math.min(height, this.maxTableHeight));  
},  
checkUserRole() {  
    const token = localStorage.getItem('token'); // 从本地存储获取 token  
    if (token) {  
      const decodedToken = jwtDecode(token); // 解码 token  
      return decodedToken.role === 'SUPERMAN'; // 检查角色  
    }  
    return false; // 无 token 返回 false  
  }, 
  saveNewOption() {  

    this.$refs.newDeptForm.validate((valid) => {  
        if (valid) {  
          addOption(this.newOption).then((response)=>{
          console.log('保存新增职位:', this.newOption);   
          this.logItem.mn = "saveNewOption";
            this.logItem.opn = "新增职位";
            this.logItem.res = "true";
            addLog(this.logItem);
          //刷新页面
          window.location.reload()  
          //关闭对话框
          this.dialogVisible = false;  
          this.newOption = [];
          this.$message.success('新职位添加成功') 
          })
        } else {  
          // 表单验证失败  
          this.logItem.mn = "saveNewOption";
            this.logItem.opn = "新增职位";
            this.logItem.res = "false";
            addLog(this.logItem);
          this.$message.success('新职位添加失败')  
          return false;  
        }  
      }); 
  },
  deleteItem(row) {  
  this.$confirm('确定要删除此选项吗?', '警告', {  
    confirmButtonText: '确定',  
    cancelButtonText: '取消',  
    type: 'warning'  
  }).then(() => {  
    // 调用删除 API  
    deleteOptionById(row.id).then(response => {  
      // 从 optionData 中移除已删除的项  
      this.optionData = this.optionData.filter(item => item.id !== row.id);  
      this.logItem.mn = "deleteItem";
          this.logItem.opn = "删除职位";
          this.logItem.res = "true";
          addLog(this.logItem);
      this.$message.success('删除成功');  
      window.location.reload()  
    }).catch(error => {  
      console.error(error);  
      this.logItem.mn = "deleteItem";
          this.logItem.opn = "删除职位";
          this.logItem.res = "false";
          addLog(this.logItem);
      this.$message.error('删除失败');  
    });  
  }).catch(() => {  
    this.$message.info('已取消删除');  
  });  
},
editItem(row) {
  this.editOption = {
    id: row.id,
    position: row.position,
    level: row.level,
    desc: row.desc,
    salary: row.salary
  };
  this.editDialogVisible = true;
},
saveEditOption() {
  this.$refs.editForm.validate((valid) => {
    if (valid) {
      updateOption(this.editOption).then(response => {
        this.$message.success('职位信息更新成功');
        this.editDialogVisible = false;
        this.logItem.mn = "saveEditOption";
            this.logItem.opn = "编辑职位信息";
            this.logItem.res = "true";
            addLog(this.logItem);
        // 刷新页面
        window.location.reload();
      }).catch(error => {
        console.error('更新失败:', error);
        this.logItem.mn = "saveEditOption";
            this.logItem.opn = "编辑职位信息";
            this.logItem.res = "false";
            addLog(this.logItem);
        this.$message.error('职位信息更新失败');
      });
    } else {
      return false;
    }
  });
},
  } 
}
</script>

<style lang="less" scoped>
.fulltable{
  margin-top: 20px;
  height: 700px;

}
.full{
  height: 800px;
  margin: 0;
  padding: 0;
  background: pink;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;
}
.add{
  padding: 10px;
}
/deep/.el-table .cell {  
  color: black;
}  
.button{
  background: #788fd3;
  color: white;
}
.paging{
  margin: 0;
  padding: 0;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;

  /deep/ .el-pagination {
    display: flex;  
    justify-content: flex-end;  
  }
}
</style>